<template>
    <div class="page" v-loading="loading">
        <tz-filter @change="filterChange" :filter-data="filterData">
            <template v-slot:default="scope">
                <el-input :maxlength="100" class="table-filter-item" v-model.trim="scope.data.ipStr" size="small" clearable placeholder="请输入ip地址"></el-input>
                <el-select class="table-filter-item" v-model="scope.data.severity" clearable size="small" placeholder="告警等级">
                    <el-option
                            v-for="item in [{id: 5, name: '一级'}, {id: 2, name: '二级'}, {id: 3, name: '三级'}]"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                    </el-option>
                </el-select>
                <el-input :maxlength="100" class="table-filter-item" v-model.trim="scope.data.name" size="small" clearable placeholder="请输入设备名称"></el-input>
                <el-input :maxlength="100" class="table-filter-item" v-model.trim="scope.data.orgName" size="small" clearable placeholder="请输入单位名称"></el-input>
            </template>
        </tz-filter>
        <div class="top-charts flex-row">
<!--            <div class="flex-row" style="position:absolute; top: -5px; z-index: 999; width: 100%">-->
<!--                <div class="flex-row flex-item flex1">-->
<!--                    <h3 style="margin: 5px;">告警总览</h3>-->
<!--                    <el-button style="margin-left: 5px" type="text" icon="el-icon-refresh" @click="alarmType = !alarmType">{{alarmType ? '城市' : '分组'}}</el-button>-->
<!--                </div>-->
<!--                <div class="flex-row flex-item flex1">-->
<!--                    <h3 style="margin: 5px;">告警处理概览</h3>-->
<!--                    <el-button style="margin-left: 5px" type="text" icon="el-icon-refresh" @click="dealType = !dealType">{{dealType ? '城市' : '分组'}}</el-button>-->
<!--                </div>-->
<!--            </div>-->
            <level-bar v-if="!loading" :chart-data="alarmLevelDetail" :isCity="viewMode.alarmType === 1" @switch="viewSwitch('alarmType')" class="flex1"></level-bar>
            <handle-bar v-if="!loading" :chart-data="alarmDealDetail" :isCity="viewMode.dealType === 1" @switch="viewSwitch('dealType')" class="flex1"></handle-bar>
        </div>
        <div class="flex-row">
            <div class="flex1"></div>
            <el-button v-if="$auth['warning_manage_strategy']" size="small" type="primary" icon="el-icon-setting" @click="showConfig">告警策略</el-button>
            <el-button v-if="$auth['warning_manage_batchDeal']" size="small" :disabled="!selectRows.length" @click="handleAlarm(selectRows)">批量处理</el-button>
            <el-button v-if="$auth['warning_manage_batchNotice']" size="small" :disabled="!selectRows.length" @click="sendMessageBatch">批量通知</el-button>
        </div>
        <br>
        <tz-table
                ref="tzTable"
                highlight-current-row
                size="mini"
                @selection-change="selectChange"
                :data="loadData">
            <el-table-column
                    type="selection"
                    fixed
                    width="55">
            </el-table-column>
            <el-table-column
                    prop="name"
                    v-if="columnConfigData.includes('设备名称')"
                    show-overflow-tooltip
                    label="设备名称"
                     :formatter="(row) => {
                   return row.name || row.ip
                 }">
                <template slot-scope="scope">
                    <high-light :value="scope.row.name" :keyword="filterData.name"></high-light>
                </template>
            </el-table-column>
            <el-table-column
                    v-if="columnConfigData.includes('告警描述')"
                    prop="summaryContent"
                    show-overflow-tooltip
                    label="告警描述"
                    :formatter="(row) => {
                       return `${row.summaryContent}`
                     }">
            </el-table-column>
            <el-table-column
                    v-if="columnConfigData.includes('单位名称')"
                    prop="resourceGroupName"
                    label="单位名称">
                <template slot-scope="scope">
                    <high-light :value="scope.row.resourceGroupName" :keyword="filterData.orgName"></high-light>
                </template>
            </el-table-column>
            <el-table-column
                    prop="ip"
                    v-if="columnConfigData.includes('ip地址')"
                    label="ip地址">
                <template slot-scope="scope">
                    <high-light :value="scope.row.ip" :keyword="filterData.ipStr"></high-light>
                </template>
            </el-table-column>
            <el-table-column
                    prop="severity"
                    width="100px"
                    v-if="columnConfigData.includes('告警等级')"
                    label="告警等级">
                <template slot-scope="scope">
                    <el-tag
                            size="mini"
                            :type="{'5': 'danger', '3': 'info', '2': 'warning'}[scope.row.severity]"
                    >{{scope.row.severity | severityToLevel}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column
                    prop="alarmNum"
                    v-if="columnConfigData.includes('告警次数')"
                    label="告警次数"
                    width="100px"
                    :formatter="(row) => {
                       return row.alarmNum || row.alarmNum === 0 ? `${row.alarmNum}` : '-'
                     }">
            </el-table-column>
            <el-table-column
                    prop="sentNum"
                    v-if="columnConfigData.includes('发送次数')"
                    label="发送次数"
                    width="100px"
                    :formatter="(row) => {
                       return row.sentNum || row.sentNum === 0 ? `${row.sentNum}` : '-'
                     }">
            </el-table-column>
            <el-table-column
                    prop="dealStatus"
                    v-if="columnConfigData.includes('状态')"
                    width="100px"
                    label="状态">
                    <template slot-scope="scope">
                        <el-tag size="mini"
                                :type="scope.row.dealStatus ? 'success' : ''"
                        >{{scope.row.dealStatus ? '已处理' : '未处理'}}</el-tag>
                    </template>
            </el-table-column>
            <el-table-column
                    prop="syncTime"
                    v-if="columnConfigData.includes('同步时间')"
                    show-overflow-tooltip
                    label="同步时间"
                    :formatter="(row) => {
                       return row.syncTime ? moment(row.syncTime).format('YYYY-MM-DD HH:mm:ss') : '-'
                     }">
            </el-table-column>
            <el-table-column
                    prop="createTime"
                    v-if="columnConfigData.includes('告警时间')"
                    show-overflow-tooltip
                    label="告警时间"
                    :formatter="(row) => {
                       return row.lastcurremce || '-'
                     }">
            </el-table-column>
            <el-table-column
                    prop="tag"
                    width="150px"
                    label="操作">
                <template slot="header">
                    <div class="flex-row flex-item">
                        <div class="flex1">操作</div>
                        <i style="font-size: 18px; cursor: pointer" class="el-icon-s-tools" @click="openColConf"></i>
                    </div>
                </template>
                <template slot-scope="scope">
                    <el-button v-if="$auth['warning_manage_deal']"
                               :disabled="!!scope.row.dealStatus"
                               @click="handleAlarm([scope.row])"
                               size="small"
                               type="text">告警处理</el-button>
                    <el-button v-if="$auth['warning_manage_notice']"
                               :disabled="!!scope.row.dealStatus"
                               @click="sendOneMessage(scope.row)"
                               size="small"
                               type="text">发送通知</el-button>
                </template>
            </el-table-column>
        </tz-table>
        <el-dialog
                title="告警策略"
                :visible.sync="configVisible"
                width="405px">
            <el-tabs v-model="severity">
                <el-tab-pane label="一级告警" name="5">
                    <alarm-config :white-list="whiteList" @close="configVisible = false" :initData="level1" level="5"></alarm-config>
                </el-tab-pane>
                <el-tab-pane label="二级告警" name="2">
                    <alarm-config :white-list="whiteList" @close="configVisible = false" :initData="level2" level="2"></alarm-config>
                </el-tab-pane>
                <el-tab-pane label="三级告警" name="3">
                    <alarm-config :white-list="whiteList" @close="configVisible = false" :initData="level3" level="3"></alarm-config>
                </el-tab-pane>
            </el-tabs>
        </el-dialog>
        <el-dialog
                title="手动发送"
                :visible.sync="sendVisible"
                width="405px">
            <el-form :model="sendForm" :rules="rules" ref="configForm" label-width="80px" v-loading="loading">
                <el-form-item label="手机号" prop="phone">
                    <el-select size="small" style="width: 260px" filterable v-model="sendForm.phone" placeholder="请输入手机号">
                        <el-option
                                v-for="item in whiteList"
                                :key="item.phone"
                                :label="item.username +' '+ item.phone"
                                :value="item.phone">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <div class="flex-row">
                        <div class="flex1"></div>
                        <el-button size="small" @click="sendVisible = false">取 消</el-button>
                        <el-button size="small" type="primary" @click="sendMessage">发送通知</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>
        <column-config ref="columnConf" @onSure="getConfig" :page-key="pageKey"></column-config>
    </div>
</template>

<script>
import moment from 'moment'
import { networks } from '@/assets/dict'
import handleBar from '@/view/warning/modules/chart/handleBar';
import levelBar from '@/view/warning/modules/chart/levelBar';
import tzTable from '@/components/tz-table'
import alarmConfig from './alarmConfig'
import {getStorage} from '@/utils/storage';
import columnConfig from '@/components/columnConfig';
// import
export default {
  name: 'manage',
  components: {
    levelBar,
    handleBar,
    tzTable,
    alarmConfig,
    columnConfig
  },
  data() {
    return {
      moment,
      pageKey: 'warning_manage_page_column_config',
      columnConfigData: null,
      columnNames: ['设备名称', '告警描述', '单位名称', 'ip地址', '告警等级', '告警次数', '发送次数', '状态', '同步时间', '告警时间'],
      whiteList: [],
      networks,
      filterData: {
        network: 'JZW',
        name: '',
        ipStr: '',
        severity: '',
        orgName: ''
      },
      loading: false,
      configVisible: false,
      sendVisible: false,
      sendForm: {
        phone: ''
      },
      sendRows: [],
      rules: {
        phone: [
          { required: true, message: '请选择接收人', trigger: 'blur' }
        ]
      },
      tableData: [],
      severity: '5',
      alarmLevelDetail: [],
      alarmDealDetail: [],
      selectRows: [],
      strategyList: [],
      defaultVal: {
        cycleType: '1',
        hours: '1',
        minutes: '1',
        phone: '',
        sendNum: 10
      },
      dealType: true,
      isEq: 0,
      faultType: true,
      analysisType: true,
      viewMode: {
        dealType: 2,
        alarmType: 2
      }
    }
  },
  computed: {
    level1() {
      return this.strategyList.find(item => {
        return +item.severity === 5
      }) || { ...this.defaultVal, severity: '5' }
    },
    level2() {
      return this.strategyList.find(item => {
        return +item.severity === 2
      }) || { ...this.defaultVal, severity: '2' }
    },
    level3() {
      return this.strategyList.find(item => {
        return +item.severity === 3
      }) || { ...this.defaultVal, severity: '3' }
    }
  },
  mounted() {
    this.getStrategy()
    this.getWhiteList()
  },
  created() {
    this.columnConfigData = getStorage(this.pageKey) || [...this.columnNames]
  },
  methods: {
    openColConf() {
      this.$refs.columnConf.open(this.columnNames)
    },
    getConfig(res) {
      this.columnConfigData = res
    },
    viewSwitch(type) {
      this.viewMode[type] = this.viewMode[type] === 1 ? 2 : 1
      this.refresh()
    },
    filterChange(res) {
      this.isEq = res.isEq
      this.refresh()
    },
    getWhiteList() {
      this.$http.get('/alarm/data/getWhiteList').then(res => {
        this.whiteList = res
      })
    },
    getStrategy() {
      this.$http.get('/alarm/data/getStrategy').then(res => {
        this.strategyList = res.map(item => {
          return { ...item, cycleType: `${item.cycleType}`}
        })
      }).catch(err => {
        this.$TZmessage.error(err.msg || '获取告警策略失败')
      })
    },
    showConfig() {
      this.configVisible = true
    },
    handleAlarm(selectRows) {
      this.$prompt('请输入备注', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: str => !str || (str.length < 50 && str.length > 0),
        inputErrorMessage: '文本不能为空且长度不超过50'
      }).then(({ value }) => {
        this.$http.post('/alarm/data/alarmDeal', {
          dealContent: value,
          idList: selectRows.map(item => item.id),
          deviceIdNetWork: selectRows
        }).then(() => {
          this.$TZmessage.success('处理成功')
        }).catch(err => {
          this.$TZmessage.error(err.msg || '处理失败')
        }).finally(() => {
          this.refresh()
        })
      }).catch(() => {
      });
    },
    sendOneMessage(row) {
      this.sendVisible = true
      switch (row.severity) {
        case '5':
          this.sendForm.phone = this.level1.phone;
          break;
        case '3':
          this.sendForm.phone = this.level3.phone;
          break;
        default:
          this.sendForm.phone = this.level2.phone;
      }
      this.sendRows = [row]
    },
    sendMessageBatch() {
      this.sendRows = [...this.selectRows]
      if (this.sendRows.length > 1) {
        this.sendForm.phone = ''
        this.sendVisible = true
      } else {
        this.sendOneMessage(this.sendRows[0])
      }
    },
    sendMessage() {
      this.$refs.configForm.validate((valid) => {
        if (!valid) {return}
        this.$http.post('/alarm/data/sendMessage', {
          deviceIdNetWork: this.sendRows,
          idList: this.sendRows.map(item => item.id),
          phone: this.sendForm.phone
        }).then(() => {
          this.$TZmessage.success('发送成功')
        }).catch(err => {
          this.$TZmessage.error(err.msg || '发送失败')
        }).finally(() => {
          this.refresh()
        })
      })
    },
    selectChange(items) {
      this.selectRows = [...items]
    },
    refresh() {
      this.$refs.tzTable.refresh(true)
    },
    loadData(params) {
      const { network, ipStr, severity, name, orgName } = this.filterData
      const { alarmType, dealType } = this.viewMode
      return this.$http.get('/alarm/data/getAlarmIndex', {
        params: {
          network,
          orgName,
          deviceName: name,
          ip: ipStr,
          isEq: this.isEq,
          alarmType,
          dealType,
          severity,
          ...params
        }
      }).then(res => {
        this.alarmLevelDetail = res.alarmLevelDetail || []
        this.alarmDealDetail = res.alarmDealDetail || []
        return {
          data: res.vo?.records || [],
          total: res.vo?.total
        }
      }).catch(err => {
        this.$TZmessage.error(err.msg || '获取列表数据失败')
      })
    },
  }
}
</script>

<style lang="scss" scoped>
    .page {
        .top-charts {
            height: 360px;
            position: relative;
        }
        ::v-deep .el-dialog__body {
            padding: 10px 20px;
        }
    }
</style>